<script setup>
import { ref, onMounted, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { getExamMasterRecord } from "@/api/pacs";
import { useArchiveStore } from "../stores/archive";
import PatientInfo from "../components/Home/PatientInfo.vue";
import ExamTable from "../components/Home/ExamTable.vue";
import { processPdfUrl } from "@/utils/pdfUrlHandler.js";

const route = useRoute();
const router = useRouter();
const archiveStore = useArchiveStore();

// 查询条件
const queryParams = reactive({
	patName: "",
	idCard: "",
	examSeq: "", // 添加检查单号参数
	requestId: "", // 添加requestId参数
	dataType: "1"
});

// 缓存上一次有效的查询参数
const cachedQueryParams = ref(null);

// 组件重新渲染的key
const examTableKey = ref(0);

// 响应式数据
const loading = ref(false);
const patientInfo = ref(null);
const patientList = ref([]);
const totalCount = ref(0);

// 从URL参数初始化查询条件
function initQueryParamsFromUrl() {
	const urlParams = route.query;

	console.log("=== URL参数调试信息 ===");
	console.log("完整URL参数:", urlParams);
	console.log("patName参数:", urlParams.patName);
	console.log("idCard参数:", urlParams.idCard);
	console.log("examSeq参数:", urlParams.examSeq);
	console.log("requestId参数:", urlParams.requestId);
	console.log("=== 调试信息结束 ===");

	// 清空之前的查询条件
	queryParams.patName = "";
	queryParams.idCard = "";
	queryParams.examSeq = "";
	queryParams.requestId = "";

	// 如果有新的URL参数，则更新
	if (urlParams.patName) queryParams.patName = urlParams.patName;
	if (urlParams.idCard) queryParams.idCard = urlParams.idCard;
	if (urlParams.examSeq) queryParams.examSeq = urlParams.examSeq;
	if (urlParams.requestId) queryParams.requestId = urlParams.requestId;

	console.log("从URL参数初始化查询条件:", queryParams);
}

// 缓存当前有效的查询参数
function cacheCurrentQueryParams() {
	if (Object.keys(route.query).length > 0) {
		cachedQueryParams.value = { ...route.query };
		console.log("缓存查询参数:", cachedQueryParams.value);
	}
}

// 查询患者基本信息
async function searchPatients() {
	try {
		loading.value = true;

		// 清空之前的archive数据，确保每次搜索都是独立的数据
		archiveStore.clearArchiveData();

		// 构建查询参数，过滤空值
		const searchParams = {
			dataType: queryParams.dataType
		};

		// 只添加非空的查询参数
		if (queryParams.patName) searchParams.patName = queryParams.patName;
		if (queryParams.idCard) searchParams.idCard = queryParams.idCard;
		if (queryParams.examSeq) searchParams.examSeq = queryParams.examSeq;
		if (queryParams.requestId) searchParams.requestId = queryParams.requestId;

		console.log("=== 搜索参数调试 ===");
		console.log("当前查询条件:", queryParams);
		console.log("发送到API的参数:", searchParams);
		console.log("=== 调试结束 ===");

		const response = await getExamMasterRecord(searchParams);
		console.log("完整API响应:", response);
		console.log("响应数据:", response.data);

		if (response.status === 200) {
			// 检查不同的可能数据结构
			const recordCS =
				response.data.recordCS || response.data.data || response.data;
			console.log("获取到检查记录:", recordCS);

			// 处理recordCS是对象的情况（包含recordCS数组）
			const records = Array.isArray(recordCS) ? recordCS : recordCS.recordCS || [];
			console.log("处理后的记录数组:", records);

			if (records && Array.isArray(records) && records.length > 0) {
				// 过滤掉检查类别为US、ES、WJ的记录（US包含US开头的检查类别）
				const filteredRecords = records.filter(record => {
					const examClass = record.examClass || "";
					const upperExamClass = examClass.toUpperCase();

					// 过滤条件：不是ES、WJ，且不以US开头
					return (
						!["ES", "WJ"].includes(upperExamClass) &&
						!upperExamClass.startsWith("US")
					);
				});

				console.log("过滤后的检查记录:", filteredRecords);

				if (filteredRecords.length > 0) {
					// 提取患者基本信息（去重）
					const uniquePatients = [];
					const seenPatients = new Set();

					filteredRecords.forEach(record => {
						const patientKey = `${record.name}-${record.idCard || ""}`;
						if (!seenPatients.has(patientKey)) {
							seenPatients.add(patientKey);
							// 确保所有字段都有值，避免显示空值
							uniquePatients.push({
								name: record.name || "未知",
								sexName: record.sexName || "未知",
								ageName: record.ageName || "未知",
								idCard: record.idCard || "未提供",
								examDateTime: record.examDateTime || "未知",
								examClass: record.examClass || "未知",
								requestDeptName: record.requestDeptName || "未知",
								reportDoctor: record.reportDoctor || "未知",
								requestDoctorName: record.requestDoctorName || "未知",
								studyInstanceUID:
									record.studyInstanceUID ||
									record.studyInstanceUid ||
									"",
								examSeq: record.examSeq || "",
								reportPrintFilePath: record.reportPrintFilePath || ""
							});
						}
					});

					patientList.value = uniquePatients;

					// 设置患者信息（使用第一个患者的信息）
					if (uniquePatients.length > 0) {
						patientInfo.value = {
							name: uniquePatients[0].name,
							sexName: uniquePatients[0].sexName,
							idCard: uniquePatients[0].idCard,
							age: uniquePatients[0].ageName
						};
					}

					totalCount.value = uniquePatients.length;
					console.log("处理后的患者信息:", uniquePatients);
					ElMessage.success(`找到${uniquePatients.length}位患者`);

					// 成功获取数据后缓存查询参数
					cacheCurrentQueryParams();
				} else {
					patientList.value = [];
					patientInfo.value = null;
					ElMessage.warning("过滤后没有找到匹配的患者信息");
				}
			} else {
				patientList.value = [];
				patientInfo.value = null;
				ElMessage.warning("没有找到匹配的患者信息");
			}
		} else {
			console.error("API调用失败:", response);
			ElMessage.error("获取患者信息失败");
		}
	} catch (error) {
		console.error("查询患者信息时出错:", error);
		ElMessage.error("查询患者信息时出错");
	} finally {
		loading.value = false;
	}
}

// 选择检查记录
function handleSelectExam(exam) {
	console.log("=== Home.vue 接收到selectExam事件 ===");
	console.log("接收到的检查记录:", exam);
	console.log("studyInstanceUID:", exam.studyInstanceUID);
	console.log("studyInstanceUid:", exam.studyInstanceUid);
	console.log("=== Home.vue 事件处理结束 ===");

	if (exam.studyInstanceUID || exam.studyInstanceUid) {
		const studyInstanceUID = exam.studyInstanceUID || exam.studyInstanceUid;
		console.log("准备跳转到dicom2d页面，studyInstanceUID:", studyInstanceUID);

		router
			.push({
				path: "/dicom2d",
				query: {
					studyInstanceUID: studyInstanceUID,
					patientName: exam.name,
					examClass: exam.examClass
				}
			})
			.then(() => {
				console.log("路由跳转成功");
			})
			.catch(error => {
				console.error("路由跳转失败:", error);
				ElMessage.error("跳转失败，请检查控制台");
			});
	} else {
		console.warn("该检查记录没有studyInstanceUID字段");
		ElMessage.warning("该检查没有可用的影像数据");
	}
}

// 查看报告
function handleViewReport(exam) {
	console.log("=== Home.vue 接收到viewReport事件 ===");
	console.log("查看报告:", exam);
	console.log("报告信息:", {
		patientName: exam.name,
		examDateTime: exam.examDateTime,
		examClass: exam.examClass,
		reportDoctor: exam.reportDoctor,
		examSeq: exam.examSeq,
		reportPrintFilePath: exam.reportPrintFilePath
	});
	console.log("=== Home.vue 报告事件处理结束 ===");

	// 检查是否有报告文件路径
	if (exam.reportPrintFilePath) {
		console.log("检测到报告文件路径:", exam.reportPrintFilePath);

		// 使用PDF URL处理器处理URL
		const pdfUrl = processPdfUrl(exam.reportPrintFilePath);
		console.log("处理后的PDF URL:", pdfUrl);

		// 跳转到PDF查看器页面
		router.push({
			name: "pdf",
			query: {
				url: pdfUrl,
				title: `${exam.name} - ${exam.examClass}报告`
			}
		});
	} else {
		console.warn("该检查记录没有报告文件路径");
		ElMessage.warning("该检查没有可用的报告文件");
	}
}

// 监听路由参数变化
watch(
	() => route.query,
	(newQuery, oldQuery) => {
		console.log("路由参数变化:", newQuery, "旧参数:", oldQuery);

		// 从URL参数初始化查询条件
		initQueryParamsFromUrl();

		// 如果有新的查询参数，缓存并搜索
		if (Object.keys(newQuery).length > 0) {
			console.log("检测到URL查询参数变化，开始自动搜索");
			cacheCurrentQueryParams();
			searchPatients();
		} else {
			// URL查询参数为空，检查是否有缓存的查询参数
			// 只有当从其他页面返回时才重新查询，避免重复触发
			if (
				cachedQueryParams.value &&
				Object.keys(cachedQueryParams.value).length > 0 &&
				Object.keys(oldQuery).length > 0 // 确保是从有参数的状态变为无参数
			) {
				console.log(
					"从其他页面返回，使用缓存的查询参数重新查询:",
					cachedQueryParams.value
				);
				// 使用缓存的参数重新查询，实现数据更新
				Object.assign(queryParams, cachedQueryParams.value);
				searchPatients();

				// 强制重新渲染ExamTable组件
				examTableKey.value++;
				console.log("强制重新渲染ExamTable组件，key:", examTableKey.value);
			} else {
				console.log("URL查询参数为空且无缓存，保持现有数据");
				// 不再清空数据，保持当前显示的患者信息
			}
		}
	},
	{ immediate: true, deep: true }
);

// 手动刷新患者数据
function refreshPatientData() {
	console.log("手动刷新患者数据");
	if (cachedQueryParams.value && Object.keys(cachedQueryParams.value).length > 0) {
		console.log("使用缓存的查询参数刷新数据:", cachedQueryParams.value);
		Object.assign(queryParams, cachedQueryParams.value);
		searchPatients();
	} else {
		console.log("没有缓存的查询参数，使用当前查询条件");
		searchPatients();
	}
}

// 页面加载时初始化
onMounted(() => {
	console.log("Home mounted, query params:", route.query);
});
</script>

<template>
	<div class="home-container">
		<!-- 头部区域 - 医院logo和标题 -->
		<div class="header">
			<div class="header-content">
				<div class="logo-section">
					<img
						src="../assets/favicon-ls.ico"
						alt="医院logo"
						class="hospital-logo"
					/>
					<div class="hospital-title">邻水县人民医院 医学影像科</div>
				</div>
			</div>
		</div>

		<!-- 主要内容区域 -->
		<div class="main-content">
			<!-- 患者信息区域 -->
			<div class="patient-section" v-if="patientInfo">
				<div class="patient-card">
					<div class="card-header">
						<div class="patient-name">
							<span class="name">{{ patientInfo.name }}</span>
							<span class="age">{{ patientInfo.age }}</span>
						</div>
						<div class="refresh-button">
							<el-button
								type="primary"
								size="small"
								@click="refreshPatientData"
								:loading="loading"
								plain
							>
								刷新数据
							</el-button>
						</div>
					</div>
					<PatientInfo
						:patient="patientInfo"
						:total-count="totalCount"
						class="patientInfo"
					/>
				</div>
			</div>

			<!-- 检查结果表格区域 -->
			<div class="result-section" v-if="patientList.length > 0">
				<ExamTable
					:key="`exam-table-${examTableKey}`"
					:patient-list="patientList"
					:loading="loading"
					@selectExam="handleSelectExam"
					@viewReport="handleViewReport"
				/>
			</div>

			<!-- 加载状态 -->
			<div class="loading-state" v-if="loading">
				<div class="loading-content">
					<div class="loading-icon">⏳</div>
					<div class="loading-text">正在加载患者信息...</div>
				</div>
			</div>
		</div>

		<!-- 脚部区域 -->
		<div class="footer">
			<div class="footer-content">
				<div class="footer-left">© 2024 邻水县人民医院</div>
				<div class="footer-right">v1.0.0</div>
			</div>
		</div>
	</div>
</template>

<style scoped>
:deep(.el-card__body) {
	padding: 4px 12px;
}

:deep(.el-card) {
	border-radius: 4px;
	border: 1px solid #e1e8e9;
	box-shadow: 0 3px 8px rgba(23, 123, 129, 0.12);
	transition: all 0.2s ease;
	background: #ffffff;
	position: relative;
	overflow: hidden;
}

:deep(.el-card::before) {
	content: "";
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	height: 2px;
	background: linear-gradient(90deg, #177b81 0%, #2a9d8f 100%);
	opacity: 0;
	transition: opacity 0.3s ease;
}

:deep(.el-card:hover) {
	box-shadow: 0 6px 16px rgba(23, 123, 129, 0.18);
	border-color: #177b81;
	transform: translateY(-2px);
	background: #ffffff;
}

:deep(.el-card:hover::before) {
	opacity: 1;
}
.home-container {
	min-height: 100vh;
	background: #fff;
	display: flex;
	flex-direction: column;
}

.header {
	background: linear-gradient(135deg, #177b81 0%, #177b81 100%);
	color: white;
	padding: 10px 0;
	box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header-content {
	max-width: 1200px;
	margin: 0 auto;
	padding: 0 20px;
	display: flex;
	justify-content: center;
	align-items: center;
	gap: 10px;
}

.logo-section {
	display: flex;
	align-items: center;
	gap: 15px;
}

.hospital-logo {
	width: 32px;
	height: 32px;
	/* border-radius: 8px; */
	object-fit: cover;
	/* border: 2px solid rgba(255, 255, 255, 0.3); */
}

.hospital-title {
	font-size: 16px;
	font-weight: 600;
	color: white;
}

.main-content {
	flex: 1;
	padding: 8px 4px;
	display: flex;
	flex-direction: column;
	gap: 8px;
	max-width: 1200px;
	margin: 0 auto;
	width: 100%;
}

.footer {
	background: #177b81;
	color: white;
	padding: 10px 0;
	margin-top: auto;
}

.footer-content {
	max-width: 1200px;
	margin: 0 auto;
	padding: 0 20px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.footer-left,
.footer-right {
	font-size: 12px;
	color: rgba(255, 255, 255, 0.8);
}

.patient-section {
	/* background: white; */
	/* border-radius: 12px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); */
	overflow: hidden;
	text-align: left;
}

.patient-card {
	padding: 0px;
}
.card-body-info {
	padding: 0;
}
.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1px solid #177b81;
	font-weight: 600;
	color: #177b81;
}

.refresh-button {
	flex-shrink: 0;
}

.patient-name {
	display: flex;
	align-items: center;
}

.patient-name .name {
	font-size: 20px;
	font-weight: 600;
}

.patient-name .age {
	font-size: 14px;
	padding: 2px 8px;
	border-radius: 12px;
}
.patientInfo {
	border-bottom: 1px solid #177b81;
}

.result-section {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.loading-state {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	background: white;
	border-radius: 12px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.loading-content {
	text-align: center;
	padding: 40px 20px;
}

.loading-icon {
	font-size: 48px;
	margin-bottom: 16px;
	opacity: 0.6;
	animation: spin 2s linear infinite;
}

.loading-text {
	font-size: 16px;
	color: #909399;
	line-height: 1.5;
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}
	100% {
		transform: rotate(360deg);
	}
}

/* 移动端适配 */
@media (max-width: 768px) {
	.header {
		padding: 8px 0;
	}

	.header-content {
		padding: 0 12px;
		flex-direction: row;
		gap: 8px;
		text-align: left;
		justify-content: flex-start;
	}

	.logo-section {
		justify-content: flex-start;
	}

	.hospital-logo {
		width: 28px;
		height: 28px;
	}

	.hospital-title {
		font-size: 13px;
		font-weight: 500;
	}

	.main-content {
		padding: 8px;
		gap: 8px;
	}

	.patient-card {
		padding: 0px;
	}

	.card-header {
		margin-bottom: 8px;
		padding-bottom: 8px;
	}

	.patient-name {
		gap: 8px;
	}

	.patient-name .name {
		font-size: 16px;
	}

	.patient-name .age {
		font-size: 11px;
		padding: 1px 4px;
	}

	.loading-content {
		padding: 20px 12px;
	}

	.loading-icon {
		font-size: 32px;
		margin-bottom: 8px;
	}

	.loading-text {
		font-size: 13px;
	}

	.footer {
		padding: 8px 0;
	}

	.footer-content {
		padding: 0 12px;
	}

	.footer-left,
	.footer-right {
		font-size: 9px;
	}
}

/* 超小屏幕手机 (320px - 480px) */
@media (max-width: 480px) {
	.home-container {
		padding: 6px;
		gap: 8px;
	}

	.patient-card {
		padding: 0px;
	}

	.patient-name .name {
		font-size: 15px;
	}

	.loading-content {
		padding: 16px 8px;
	}

	.loading-icon {
		font-size: 28px;
	}

	.loading-text {
		font-size: 12px;
	}
}

/* 平板设备适配 (769px - 1024px) */
@media (min-width: 769px) and (max-width: 1024px) {
	.home-container {
		padding: 15px;
		gap: 18px;
	}

	.patient-card {
		padding: 0px;
	}

	.patient-name .name {
		font-size: 19px;
	}
}

/* 大屏幕适配 (1025px+) */
@media (min-width: 1025px) {
	.home-container {
		max-width: 1200px;
		margin: 0 auto;
	}
}
</style>
